//
//  BeanORM.m
//  storeapp
//
//  Created by huangyi on 13-4-17.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "BeanDatabase.h"
#import "Bean.h"

#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "FMDatabasePool.h"
#import "FMDatabaseQueue.h"

@interface BeanDatabase ()

@property(nonatomic,strong)FMDatabase *db;

@end

@implementation BeanDatabase

-(id)initWithDatabase:(NSString*)filename{
    self=[super init];
    if (self) {
        self.db=[FMDatabase databaseWithPath:filename];
        self.db.logsErrors=YES;
        [self.db open];
    }
    return self;
}
-(void)closeDatabase{
    [self.db close];
}

-(FMDatabase*)getFMDB{
    return self.db;
}

-(BeanTable*)getTable:(NSString*)tablename{
    BeanTable *table=[[BeanTable alloc] init];
    table.tableName=tablename;
    table.db=self;
    return table;
}
-(BeanObject*)dispense:(NSString*)tablename{
    BeanTable *table=[self getTable:tablename];
    BeanObject *obj=[table dispense];
    return obj;
}

-(NSArray*)getTableNames{
    FMResultSet *set=[self.db getSchema];
    NSMutableArray *tables=[NSMutableArray array];
    while ([set next]) {
        NSDictionary *row=set.resultDictionary;
        if ([row[@"type"] isEqualToString:@"table"]) {
            [tables addObject:row[@"name"]];
        }
    }
    return tables;
}

@end
